package com.itany.shop.tran.impl;

import com.itany.shop.exception.DataAccessException;
import com.itany.shop.tran.TransactionManager;
import com.itany.shop.util.JDBCUtil;

import java.sql.SQLException;

/**
 * @author 黄衡熙
 * @version 1.0
 */
public class TransactionManagerImpl implements TransactionManager{
    @Override
    public void begin() {
        try {
            JDBCUtil.getConnection().setAutoCommit(false);
        } catch (SQLException e) {
            throw new DataAccessException("事务开启失败");
        }
    }

    @Override
    public void commit() {
        try {
            // 当且仅当,当前设置的是手动事务时才需要提交
            if (!JDBCUtil.getConnection().getAutoCommit()) {
                JDBCUtil.getConnection().commit();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new DataAccessException("事务提交失败");
        } finally {
            // 事务结束后需要释放线程池的资源
            JDBCUtil.close();
        }
    }

    @Override
    public void rollback() {
        try {
            // 当且仅当,当前设置的是手动事务时才需要回滚
            if (!JDBCUtil.getConnection().getAutoCommit()) {
                JDBCUtil.getConnection().rollback();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new DataAccessException("事务提交失败");
        } finally {
            // 事务结束后需要释放线程池的资源
            JDBCUtil.close();
        }
    }
}
